package com.example.admin.smstest.sms;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.admin.smstest.ConnectionManager;
import com.example.admin.smstest.DeviceActivity;
import com.example.admin.smstest.R;
import com.example.admin.smstest.permission.CheckPermissionsActivity;
import com.example.admin.smstest.utils.ByteUtil;
import com.example.admin.smstest.utils.CrcOperateUtil;
import com.example.admin.smstest.utils.DataUtil;
import com.example.admin.smstest.utils.DateUtil;
import com.example.admin.smstest.utils.SharedPreferencesUtils;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import static com.example.admin.smstest.utils.ByteUtil.hexStringToBytes;
import static com.example.admin.smstest.utils.ByteUtil.intToHexBytes;

/**
 * 监听短信信号，发送与接受--测试类
 * Created by yangjx on 2017/4/1.
 */
public class SmsActivity extends CheckPermissionsActivity {

    private static final String TAG = SmsActivity.class.getSimpleName();
    private ConnectionManager mConnectionManager;//链接监听类
    private SmsObserver smsObserver;
    private TextView textView;
    private Button conBt;
    private Button sendBt;
    private String smsInfo;
    private Uri SMS_INBOX = Uri.parse("content://sms/");
    private final int RESULT_CODE_BTDEVICE = 0;
    private Cursor cursor = null;
    private int first = 0;
    private int second = 0;
    private String smsIdFirst;
    private String smsIdSecond;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms);
        initView();
        initSmsObserver();
        SharedPreferencesUtils sp = SharedPreferencesUtils.getInstance(SmsActivity.this,"sms_data");
        if (!sp.get("device_address","").toString().equals("")){
            String address = sp.get("device_address","").toString();
            mConnectionManager = new ConnectionManager(mConnectionListener);
            mConnectionManager.connect(address);
            mConnectionManager.startListen();
        }
    }

    /**
     * 初始化页面
     */
    private void initView(){
        textView = (TextView) findViewById(R.id.text);
        conBt = (Button) findViewById(R.id.con_bt);
        conBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(SmsActivity.this, DeviceActivity.class);
                startActivityForResult(i, RESULT_CODE_BTDEVICE);
            }
        });
        sendBt = (Button) findViewById(R.id.send_button);
        sendBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {}
        });
    }

    //初始化短信observer
    private void initSmsObserver(){
        smsObserver = new SmsObserver(this, new Handler());
        getContentResolver().registerContentObserver(SMS_INBOX, true,
                smsObserver);
    }

    /**
     * 发送短信数据
     * @param date
     * @param id
     * @param numbers
     * @param body
     * @throws UnsupportedEncodingException
     */
    private void sendMessage(String date,String id,String numbers,String body,String type) throws UnsupportedEncodingException{
        // 1.帧头
        byte[] frameHeader = DataUtil.MAGICTYPES;
        // 2.作用域
        byte[] function = DataUtil.FUNCTION;
        //                   序列号|业务号|操作类型 (type)| Type(TLV)
        byte[] baowentou = {  0x01,  0x05,        0x03,        0x01};// 10B

        // value的长度
        // a.时间
        byte[] timeB = hexStringToBytes(date);
        // b.destination  1==接受 2==发送
        byte[] destinationB = ByteUtil.intToHexBytes(Integer.parseInt(type));
        // c.Short message ID number
        int idI = Integer.parseInt(id,10);
        byte[] idB = ByteUtil.intToHexBytes(idI);
        // d.number 短信的电话号码
        byte[] numberB = ByteUtil.getByte(numbers);
        // e.获取当前的短信内容

        byte[] smsValueB = null;
        if (body.length() <= 100){
            byte[] totalB = {0x01,0x00};
            byte[] totalC = {0x01,0x00};
            byte[] bodyByte= ByteUtil.getByte(body);
            // TLV中的Value
            smsValueB = ByteUtil.concatAll(timeB,destinationB,idB,numberB,bodyByte);
            // 3.短信长度
            byte[] smsByteLength = ByteUtil.intToHexBytes(smsValueB.length);
            // 4.TLV长度
            byte[] valueTotalLength = ByteUtil.intToHexBytes(smsValueB.length+7);
            // 加crc校验
            byte[] andData = ByteUtil
                    .concatAll(function,valueTotalLength ,totalB,totalC,baowentou,smsByteLength,smsValueB);
            byte[] endData = CrcOperateUtil.setParamCRC(andData);
            byte[] data = ByteUtil.concatAll(frameHeader, endData);
            mConnectionManager.sendData(data);
            System.out.println(Arrays.toString(data));
            boolean sendSuccess = mConnectionManager.sendData(data);
            System.out.println("发送成功？"+sendSuccess);
        }else{
            int total = body.length()/100 + 1;
            //总包数totalB为真实值
            byte[] totalB = ByteUtil.getPackets(total);
            for(int i = 0;i < total ;i++){
                System.out.println("一共几个包"+total);
                if(i != total -1){
                    //当前报数
                    byte[] totalC = ByteUtil.getPackets(i+1);
                    String body1 = body.substring(i*100,(i+1)*100);
                    byte[] bodyByte= ByteUtil.getByte(body1);
                    // TLV中的Value
                    smsValueB = ByteUtil.concatAll(timeB,destinationB,idB,numberB,bodyByte);
                    // 3.短信长度
                    byte[] smsByteLength = ByteUtil.intToHexBytes(smsValueB.length);
                    // 4.TLV长度
                    byte[] valueTotalLength = ByteUtil.intToHexBytes(smsValueB.length+7);
                    // 加crc校验
                    byte[] andData = ByteUtil
                            .concatAll(function,valueTotalLength ,totalB,totalC,baowentou,smsByteLength,smsValueB);
                    byte[] endData = CrcOperateUtil.setParamCRC(andData);

                    byte[] data = ByteUtil.concatAll(frameHeader, endData);
                    System.out.println("长度=="+data.length);
                    System.out.println(Arrays.toString(data));
                    boolean sendSuccess = mConnectionManager.sendData(data);
                    System.out.println("发送成功？"+sendSuccess);
                }else if(i == (total - 1)){
                    //当前报数，最后一个包名
                    byte[] totalC = ByteUtil.getPackets(i+1);
                    String body1 = body.substring(i*100,body.length());
                    byte[] bodyByte= ByteUtil.getByte(body1);
                    // TLV中的Value
                    smsValueB = ByteUtil.concatAll(timeB,destinationB,idB,numberB,bodyByte);
                    // 3.短信长度
                    byte[] smsByteLength = ByteUtil.intToHexBytes(smsValueB.length);
                    // 4.TLV长度
                    byte[] valueTotalLength = ByteUtil.intToHexBytes(smsValueB.length+7);
                    // 加crc校验
                    byte[] andData = ByteUtil
                            .concatAll(function,valueTotalLength ,totalB,totalC,baowentou,smsByteLength,smsValueB);
                    byte[] endData = CrcOperateUtil.setParamCRC(andData);
                    byte[] data = ByteUtil.concatAll(frameHeader, endData);
                    mConnectionManager.sendData(data);
                }
            }
        }

                //System.out.println("发送"+Arrays.toString(data));
               // boolean sendSuccess = mConnectionManager.sendData(data);
               // System.out.println("发送成功？"+sendSuccess);
           // }
        //}
    }

    /**
     * 链接监听
     */
    private ConnectionManager.ConnectionListener mConnectionListener = new ConnectionManager.ConnectionListener() {

        @Override
        public void onConnectStateChange(int oldState, int State) {
        }

        @Override
        public void onListenStateChange(int oldState, int State) {
        }

        @Override
        public void onSendData(boolean suc, byte[] data) throws UnsupportedEncodingException {
            System.out.println("发送监听："+ Arrays.toString(data));
            //getData(data);
        }

        @Override
        public void onReadData(byte[] data) {
            //System.out.println("接收："+Arrays.toString(data));
            //getData(data);
        }
    };

//-----------------------------------------------------------------------短信模块---------------------------
    /**
     * 短信观察者
     */
    public class SmsObserver extends ContentObserver {

        public SmsObserver(Context context, Handler handler) {
            super(handler);
        }

        @Override
        public void onChange (boolean selfChange) {
            super.onChange(selfChange);
            onChange(selfChange, null);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {

            /**
             * 适配某些较旧的设备，可能只会触发onChange(boolean selfChange)方法，没有传回uri参数，
             * 此时只能通过"content://sms/inbox"来查询短信
             */
            getSendSms(uri);
           // getReceiveSms(uri);
        }
    }

    public void getReceiveSms(Uri uri) {
        if (uri == null) {
            uri = Uri.parse("content://sms/inbox");
        }
        if (uri.toString().equals("content://sms/raw")) {
            return;
        }
        try {
            cursor = getContentResolver().query(
                    Uri.parse("content://sms/inbox"), null, null,
                    null,
                    "date desc");
            if(cursor!=null){
                if(cursor.moveToNext()){//不遍历只拿当前最新的一条短信 moveToFirst() moveToNext()
                    String smsId = cursor.getString(cursor.getColumnIndex("_id"));
                    if (!smsId.equals(smsIdFirst)){
                        if (first == 0){
                            smsIdFirst = smsId;
                            first++;
                        }else{
                        System.out.println("smsId inbox=="+smsId);
                        smsIdFirst = smsId;
                        String date = DateUtil.getTime(System.currentTimeMillis());//时间
                        String type = cursor.getString(cursor.getColumnIndex("type"));;//状态 1==接受短信 2==发送短信
                        String id = cursor.getString(cursor.getColumnIndex("thread_id"));//id 短信Id
                        String address = cursor.getString(cursor.getColumnIndex("address"));// 短信号码
                        String body = cursor.getString(cursor.getColumnIndex("body"));
                        cursor.close();
                        first++;
                        System.out.println("type=="+type);
                        System.out.println(body);
                        // 已经有了sms 做任何你想做的事情
                        sendMessage(date,id,address,body,type);
                        }
                    }
                }
            }else{
                Log.e(TAG, "error: cursor == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(cursor!=null){cursor.close();}
        }
    }

    public void getSendSms(Uri uri){
        if (uri == null) {
            uri = Uri.parse("content://sms/sent");
        }
        if (uri.toString().equals("content://sms/raw")) {
            return;
        }
        try {
            cursor = getContentResolver().query(
                    Uri.parse("content://sms/sent"), null, null,
                    null,
                    "date desc");
            if(cursor!=null){
                if(cursor.moveToFirst()){//不遍历只拿当前最新的一条短信 moveToFirst() moveToNext()
                    String smsId = cursor.getString(cursor.getColumnIndex("_id"));
                    if (!smsId.equals(smsIdSecond)){
                        if (second == 0){
                            smsIdSecond = smsId;
                            second++;
                        }else{
                            System.out.println("smsId sent=="+smsId);
                            smsIdSecond = smsId;
                            String date = DateUtil.getTime(System.currentTimeMillis());//时间
                            String type = cursor.getString(cursor.getColumnIndex("type"));;//状态 1==接受短信 2==发送短信
                            String id = cursor.getString(cursor.getColumnIndex("thread_id"));//id 短信Id
                            String address = cursor.getString(cursor.getColumnIndex("address"));// 短信号码
                            String body = cursor.getString(cursor.getColumnIndex("body"));
                            cursor.close();
                            System.out.println("type=="+type);
                            System.out.println(body);
                            // 已经有了sms 做任何你想做的事情
                            second++;
                            sendMessage(date,id,address,body,type);
                        }
                    }
                }
            }else{
                Log.e(TAG, "error: cursor == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(cursor!=null){cursor.close();}
        }
    }
}

//
//sms主要结构：
//        　　_id：短信序号，如100
//        　　thread_id：对话的序号，如100，与同一个手机号互发的短信，其序号是相同的
//        　　address：发件人地址，即手机号，如+86138138000
//        　　person：发件人，如果发件人在通讯录中则为具体姓名，陌生人为null
//        　　date：日期，long型，如1346988516，可以对日期显示格式进行设置
//        　　protocol：协议0SMS_RPOTO短信，1MMS_PROTO彩信
//        　　read：是否阅读0未读，1已读
//        　　status：短信状态-1接收，0complete,64pending,128failed
//        　　type：短信类型1是接收到的，2是已发出
//        　　body：短信具体内容
//        　　service_center：短信服务中心号码编号，如+8613800755500
